/*************************************
 * Created by WebStorm
 * Author : 菲尔敦
 * QQ邮箱：2891044172@qq.com  手机号：15981761402
 * Created Time :2024/2/5 18:39
 Desc :
 **************************************/

/**
 * Created by WebStorm
 * User : 艾尼亚尔·毛拉吾提
 * Date :2023/5/29
 * Time :16:14
 */
import {http} from '@/util/http/index.ts';
import {downloadEvt, transformRequestData} from '@/util';
import {isObject,isArray} from "@/util/is.ts";
import {getToken} from '@/util/Auth.ts';



/**
 * post请求
 * @param url 请求地址
 * @param params  参数
 */
export function postRequest(url: string, params: any) {
    return http.request({
            url: url,
            method: 'POST',
            params,
        }
    );
}

/**
 * get请求
 * @param url 请求地址
 * @param params 参数
 * @param rule 传参数模式  默认:false  false是:xxx/xxx?name=xxx  true是: xxx/xxx/{name}
 */
export function getRequest(url: string, params: any = null, rule: boolean = false) {
    let urls = url;
    if (rule) {
        for (const item in params) {
            urls += '/'+params[item];
        }
        return http.request({
                url: urls,
                method: 'GET',
            }
        );
    } else {
        return http.request({
                url: urls,
                method: 'GET',
                params,
            }
        );
    }
}

/**
 * post put请求
 * @param url 请求地址
 * @param params 参数
 * @param method  请求模式 默认：POST
 */
export function postPutRequest(url: string, params: any, method: string = 'POST') {
    return http.request({
            url: url,
            method: method,
            params,
        }
    );
}

/**
 * delete请求
 * @param url 请求地址
 * @param params 参数
 */
export function delRequest(url: string, params: any) {
    if (!isObject(params) && !isArray(params)) {
        return http.request({
                url:  url + '/' + params,
                method: 'DELETE'
            }
        );
    } else {
        return http.request({
                url:  url,
                method: 'DELETE',
                params,
            }
        );
    }
}
export function uploadFileRequest(url: string, params: any) {
    return http.request({
            url: url,
            method: 'POST',
            params,
            headers: {'Content-Type': 'multipart/form-data'}
        }
    );
}

/**
 * 下载文件
 * @param url
 * @param params
 * @param config
 * @param method
 */
export function downloadFile(url: string, params: any | null = {}, config: Object | null = {}, method: string = 'get') {
    const $notification = window['$notification'];
    // const appStore = UseAppStore();
    const _method: string = method.toUpperCase();
    const _config: { contentType: string, fileName: string, async: boolean, token: string } = Object.assign({
        contentType: _method === 'GET' ? 'application/x-www-form-urlencoded;charset=UTF-8' : 'application/json;charset=UTF-8',//请求头类型
        fileName: '未知文件', //下载文件名(必填，若为空，下载下来的都是txt格式)
        async: true, //请求是否异步  true：异步  false：同步
        token: getToken(),
    }, config)
    const queryParams: string | FormData = transformRequestData(_config.contentType, params != null ? params : {});
    const _url: string = `/api/${url}${_method === 'GET' && queryParams ? '?' + queryParams : ''}`;
    const xhr: XMLHttpRequest = new XMLHttpRequest();
    xhr.open(_method, _url, _config.async);
    xhr.setRequestHeader('Authorization','Bearer '+_config.token);
    xhr.setRequestHeader('Content-type', _config.contentType);
    xhr.responseType = 'blob';
    //获取文件下载进度
    xhr.addEventListener('progress', (progress: ProgressEvent<XMLHttpRequestEventTarget>): void => {
        const percentage: number = ((progress.loaded / progress.total) * 100);
        if (percentage==100){
            $notification.success({
                title:params.name+'下载完成',
                duration: 1500,
            })
        }
        // const msg: string = `下载进度 ${percentage}%...`;
        // appStore.setDynamicDownloadProgress(percentage);
        // console.log(msg)
    })
    xhr.onload = function () {
        if (xhr.status === 200 || xhr.status === 304) {
            //通过FileReader去判断接口返回的是json还是文件流
            const fileReader = new FileReader();
            fileReader.onloadend = (_e: ProgressEvent<FileReader>): void => {
                const content_type: string | null = xhr.getResponseHeader('Content-Type') || '';
                const contentDescription: string | null = xhr.getResponseHeader('content-disposition');
                let fileName: string = contentDescription && contentDescription.split('filename=')[1] || '';
                // let size: string = xhr.getResponseHeader('Content-Length') || '0';
                if (content_type && content_type.includes('application/json')) {
                    $notification.success({
                        title:params.name+'下载完成',
                        duration: 1500,
                    })
                    console.log('当前文件不存在')
                } else {
                    const isFileNameCorrupted = /[^\x00-\x7F]/.test(fileName);
                    if (isFileNameCorrupted) {
                        const fileExtension = fileName.split('.').pop();
                        fileName = params.name + '.' + fileExtension;
                    }
                    fileName = fileName.replace(/"/g, '');
                    const blob = new Blob([xhr.response], {type: content_type});
                    downloadEvt(blob, fileName)

                }
            }
            fileReader.readAsText(this.response)
        } else {
            console.log('服务器出现问题，请联系管理员')
        }
    }
    if (_method === 'POST') {
        xhr.send(queryParams)
    } else {
        xhr.send()
    }
}





